from flask import Flask, session, render_template, redirect, Blueprint, request

# 导入数据库配置类
from config import Config

# sqlAlchemy
from db import db

# 正则匹配
import re

app = Flask(__name__)
# 要放在 app = Flask(__name__) 之后
# 传入page页面的page.py文件
from views.page import page
# 传入user页面的user.py文件
from views.user import user
# 使用page
app.register_blueprint(page.pb)
app.register_blueprint(user.ub)

# 使用数据库配置类
app.config.from_object(Config)

# 数据库初始化
db.init_app(app)


# /主页面跳转到login页面
@app.route('/')
def index():  # put application's code here
    return redirect('/user/login')

# 生命周期函数
@app.before_request
def before_request():
    pat = re.compile(r'^/static')
    if re.search(pat, request.path):
        return
    if request.path == '/user/login':
        return
    if request.path == '/user/register':
        return
    uname = session.get('username')
    if uname:
        return None

    return redirect('/user/login')

# 匹配其他未知页面时
@app.route('/<path:path>')
def catch_all(path):
    return render_template('404.html')

if __name__ == '__main__':
    app.run()
